package com.atguigu.tingshu.user.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.aspectj.bridge.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitService rabbitService;
    /**
     * 获取声音的上次跳出时间
     * @param trackId
     * @return
     */
    @Override
    public BigDecimal getTrackBreakSecond(Long trackId) {
        Long userId = AuthContextHolder.getUserId();
        if(userId.intValue()!=0){
            //先查询是否mongodb库 userid trackid
            Query query=new Query();
            query.addCriteria(Criteria.where("userId").is(userId).where("trackId").is(trackId));
            UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
            if(userListenProcess!=null){
                return userListenProcess.getBreakSecond();
            }
        }
        return new BigDecimal("0");
    }

    /**
     * 更新播放进度
     * @param userListenProcessVo
     * @param userId
     */
    @Override
    public void updateListenProcess(UserListenProcessVo userListenProcessVo,Long userId) {
        //判断MongoDB中是否有该用户的数据 userid albumid trackid breakSecond
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId)
                .where("albumId").is(userListenProcessVo.getAlbumId())
                .where("trackId").is(userListenProcessVo.getTrackId())
        );
        query.limit(1);
        UserListenProcess userProcesses = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));

        if(userProcesses==null){
            //第一次播放
            UserListenProcess userListenProcess = new UserListenProcess();
            userListenProcess.setId(IdUtil.getSnowflakeNextIdStr());
            userListenProcess.setUserId(userId);
            userListenProcess.setAlbumId(userListenProcessVo.getAlbumId());
            userListenProcess.setTrackId(userListenProcessVo.getTrackId());
            userListenProcess.setIsShow(1);
            userListenProcess.setCreateTime(new Date());
            userListenProcess.setUpdateTime(new Date());
            userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
        }else {
            //有记录
            userProcesses.setUpdateTime(new Date());
            userProcesses.setBreakSecond(userListenProcessVo.getBreakSecond());
        }
        mongoTemplate.save(userProcesses);
        String mongoKey=RedisConstant.USER_TRACK_REPEAT_STAT_PREFIX+userListenProcessVo.getTrackId()+":"+userId;
        //设置过期时间当天还剩时间作为过期时间
        long ttl = DateUtil.endOfDay(new Date()).getTime() - System.currentTimeMillis();

        Boolean flags = redisTemplate.opsForValue().setIfAbsent(mongoKey, userListenProcessVo.getTrackId(),ttl, TimeUnit.MICROSECONDS);

        if(flags){
            //一天在第一次记录
            TrackStatMqVo trackStatMqVo=new TrackStatMqVo();
            trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
            trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
            trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
            trackStatMqVo.setCount(1);
            trackStatMqVo.setBusinessNo(IdUtil.getSnowflakeNextIdStr());
            rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,MqConst.ROUTING_TRACK_STAT_UPDATE, trackStatMqVo);
        }


    }

    @Override
    public Map<String,Long> getLatelyTrack(Long userId) {
        Map<String,Long> map = new HashMap<>();
        if (userId.intValue()!=0){
            // userid
            Query query = new Query();
            query.addCriteria(Criteria.where("userId").is(userId)
            );

            query.with(Sort.by(Sort.Direction.DESC,"updateTime"));
            query.limit(1);
            UserListenProcess userProcesses = mongoTemplate.findOne(query, UserListenProcess.class,
                    MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
            map.put("albumId",userProcesses.getAlbumId());
            map.put("trackId",userProcesses.getTrackId());
            return map;
        }
        return map;
    }
}
